package cn.com.callback

import groovy.json.*;
import groovy.swing.impl.DefaultAction
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.crypto.Cipher
import javax.crypto.SecretKey
import javax.crypto.spec.SecretKeySpec
import javax.servlet.RequestDispatcher;
import cn.com.callback.CallBackInvoke
import cn.com.callback.ServiceBackInvoke
import cn.com.elite.EliteBean;
import cn.com.elite.Util;
import java.security.MessageDigest;
import java.sql.ResultSet;
import java.text.ParseException
import java.text.SimpleDateFormat;
import java.time.Instant
import org.apache.commons.codec.binary.Base64
import org.apache.commons.codec.digest.DigestUtils
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject

import cn.com.kh.KHUtil;
import cn.com.kh.hst.ThreeDesUtil;
import cn.com.kh.getProperty;
import java.net.URLEncoder;



/**
 *
 * @Title: api_SmsSend
 * @Description:华盛证券 短信发送 --内部接口
 * @author: xpf
 * @date 2021-07-07 10:28:00
 *
 */

public class api_SmsSend implements ServiceBackInvoke {
	private static final Log log = LogFactory.getLog(api_SmsSend.class);

	public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

		response.setCharacterEncoding("UTF-8");

		String getMethod = request.getMethod();
		log.debug("getMethod:" + getMethod);

		String inData = "";
		String outData = "";
		String outcount;
		String dataSourceID = "dataSource";
		String msg="";

		BufferedReader iny = null;
		if (getMethod.equals("GET")) {
			inData = request.getParameter("data");
			log.debug("原始Get请求参数:" + inData);
		} else {
			InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
			iny = new BufferedReader(reader);
			String line;
			while ((line = iny.readLine()) != null) {
				inData += line;
			}
			log.debug("原始Post请求参数:" + inData);
		}

		try {
			def getSmsSelectSQL = eliteBean.chaxun_sql("select DOCUMENTOUT_GUID,documentto,documentpath,sub_doctype,hst_no,areacode,phonetitle,d.CREATEDDATE,s.Stringfield1,TRIALCOUNT,TRIALCOUNTLIMIT from documentout d left join staff s on d.CREATEDBY=STAFF_ID where STATUS=0 and doctype=3 and TRIALCOUNT<3 ORDER BY TRIALCOUNT asc", "dataSource");
			log.debug("SQL获取数据:" + getSmsSelectSQL);	
			if (getSmsSelectSQL.size() > 0) {
				log.debug("job_SmsSend开始处理短信发送任务--------------------------");
				String appid = getProperty.get("appid");
				String appsecret = getProperty.get("appsecret");
				String token="";
				String DOCUMENTTO = "";        //手机号码
				String documentpath = "";    //短信内容
				String sub_doctype = "";	//类型
				String hst_no="";	//华盛号
				String areacode="";	//区号
				String CREATEADATE=""; //创建时间
				String phonetitle=""; //标题
				String DOCUMENTOUT_GUID=""; //guid
				String sign = "";
				String sign_str = "";
				String signfront="";
				String signafter="";
				int TRIALCOUNT;
				int count_lmt;
				String sizi=getSmsSelectSQL.size();//总发送短信数
				log.debug("总发送短信数：" + sizi);
				def remoteAddr = ThreeDesUtil.getIpAddr(request);
				int count=0;//短信发送成功数
				for (int i = 0; i < getSmsSelectSQL.size(); i++) {
					DOCUMENTTO = getSmsSelectSQL.get(i).get("DOCUMENTTO");
					documentpath = getSmsSelectSQL.get(i).get("documentpath");
					sub_doctype=getSmsSelectSQL.get(i).get("sub_doctype");
					hst_no = getSmsSelectSQL.get(i).get("hst_no");
					areacode = getSmsSelectSQL.get(i).get("areacode");
					CREATEADATE=getSmsSelectSQL.get(i).get("CREATEADATE");
					phonetitle=getSmsSelectSQL.get(i).get("phonetitle");
					token=getSmsSelectSQL.get(i).get("Stringfield1");
					DOCUMENTOUT_GUID=getSmsSelectSQL.get(i).get("DOCUMENTOUT_GUID");
					TRIALCOUNT=getSmsSelectSQL.get(i).get("TRIALCOUNT");
					log.debug("短信发送号码：" + DOCUMENTTO + ",内容：" + documentpath + ",sub_doctype:" + sub_doctype+ ",hst_no:" + hst_no+ ",areacode:" + areacode+ ",CREATEADATE:" + CREATEADATE);
					//获取时间戳
					String sign_time=Instant.now().getEpochSecond();
					//判断是否手机号发送
					HashMap<String, String> paramHashMap = new HashMap<String, String>()
					HashMap<String, String> paramHashMap1 = new HashMap<String, String>()
					if(sub_doctype=="1" && TRIALCOUNT<=3) {
						log.debug("sub_doctype为1。。。。。。。")
									paramHashMap.put("token", token);
									paramHashMap.put("subject", phonetitle);
									paramHashMap.put("content", documentpath);
									paramHashMap.put("mobile", DOCUMENTTO+","+areacode);
									paramHashMap.put("sign_time", sign_time);
									//paramHashMap.put("remoteAddr", remoteAddr);

									//处理特殊字符 URLEncoder
									paramHashMap1.put("token", token);
									paramHashMap1.put("subject", phonetitle);
									paramHashMap1.put("content", URLEncoder.encode(documentpath, "utf-8"));
									paramHashMap1.put("mobile", DOCUMENTTO+","+areacode);
									paramHashMap1.put("sign_time", sign_time);
					}
					//判断是否华盛号发送
					if(sub_doctype=="2" && TRIALCOUNT<=3) {
						log.debug("sub_doctype为2。。。。。。。")
									paramHashMap.put("token", token);
									paramHashMap.put("subject", phonetitle);
									paramHashMap.put("content", documentpath);
									paramHashMap.put("hsNo", hst_no);
									paramHashMap.put("sign_time", sign_time);
									//paramHashMap.put("remoteAddr", remoteAddr);

									//处理特殊字符 URLEncoder
									paramHashMap1.put("token", token);
									paramHashMap1.put("subject", phonetitle);
									paramHashMap1.put("content", URLEncoder.encode(documentpath, "utf-8"));
									paramHashMap1.put("hsNo", hst_no);
									paramHashMap1.put("sign_time", sign_time);
							}		
							log.debug("paramHashMap：" + paramHashMap);
							//自然排序 升序参数
							signfront= ThreeDesUtil.sortMap(paramHashMap,appid,appsecret);
							log.debug("sign加密MD5前：" + signfront);
							signafter = Util.getMD5Str(signfront);
							log.debug("sign加密MD5后：" + signafter);
							TRIALCOUNT+=1;
							paramHashMap1.put("client_key", appid);
							paramHashMap1.put("sign", signafter);
							log.debug("限制次数：" + TRIALCOUNT);
							String injson=ThreeDesUtil.SplicingMap(paramHashMap1,"&");
							log.debug("发送地址&拼接后："+ injson);
							outcount=Sendsms(eliteBean, injson,DOCUMENTOUT_GUID,dataSourceID,TRIALCOUNT);
							//outData+=outData;
							count+=Integer.parseInt(outcount);							
						}
						msg = "当前批次共有" + sizi + "条数据，成功插入" + count + "条！";
						log.debug("当前需要发送短信的数据处理结果:" + msg);
				}else {
						log.debug("job_SmsSend当前无短信发送任务--------------------------");
				}

			outData = "{\"code\":\"1\",\"message\":\"成功\",\"data\":{\"custtype\":\"" + 1 + "\"}}";
				//log.debug("返回Json:" + reJoson);

			} catch (Exception e) {
				log.error("接口处理异常" + e.getMessage());
				// 失败返回
			outData = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(" + e.getMessage() + ")\",\"data\":[]}";
			}
				//log.debug("处理完成返回结果:" + outData);
				return outData;
	}
	//
	public static String Sendsms(EliteBean eliteBean , String injson,String DOCUMENTOUT_GUID, String dataSourceID,int TRIALCOUNT) {

		long startTime = System.currentTimeMillis();
		log.debug("处理开始时间:" + startTime);

		long endTime = System.currentTimeMillis();

		String reJson = null;
		try {
			
			String doURL = getProperty.get("HSTURL");
			doURL = doURL+"/msg/mobile/send";
			
			Map<String, String> headMap = new HashMap<String, String>();
			headMap.put("Content-Type", "application/x-www-form-urlencoded");
			def getResult = Util.doHttpPostUseHead(doURL, injson, "UTF-8", 10000, 0, headMap);
			log.debug("getResult:" + getResult);
			
			//解析SSO返回信息
			JSONObject jsonObject = new JSONObject(getResult);
			String code = GetJV(jsonObject, "code");
			String result = GetJV(jsonObject, "result");
			
			log.debug("code:" + code);
			if(code == "00000") {
				//返回认证信息成功
				def updatesamp = eliteBean.update("Update documentout Set STATUS = 1, MODIFIEDDATE = NOW() ,FINISHDATETIME=NOW(), TRIALCOUNT='" + TRIALCOUNT + "' WHERE DOCUMENTOUT_GUID = '" + DOCUMENTOUT_GUID + "'", "dataSource");
				reJson = 1;
				log.debug("{\"result\":\"1\",\"message\":\"短信发送成功\"}");
				log.debug('修改的次数：'+TRIALCOUNT);
			}else{
				def updatesamp1 = eliteBean.update("Update documentout Set TRIALCOUNT='" + TRIALCOUNT + "' WHERE DOCUMENTOUT_GUID = '" + DOCUMENTOUT_GUID + "'", "dataSource");
				reJson = 1;
				log.debug("{\"result\":\"-1\",\"message\":\"短信发送失败\"}");
				log.debug('修改的次数：'+TRIALCOUNT);
			}



		} catch (JSONException e) {
			log.error("接口处理异常" + e.getMessage());
			// 失败返回
			//reJson = 2;
			log.debug("{\"result\":\"-1\",\"message\":\"短信发送失败\"}");
		}

		return reJson;
	}


	// 解析Json值
	public static String GetJV(JSONObject inJson, String getKey) {
		String Rev_Value = null;
		try {
			Rev_Value = inJson.getString(getKey);
		} catch (Exception e) {
			try {
				Rev_Value = String.valueOf(inJson.getInt(getKey));
			} catch (Exception e1) {
				try {
					Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
				} catch (Exception e2) {
					try {
						Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
					} catch (Exception e3) {
						Rev_Value = "";
					}
				}
			}
		} finally {
			if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
				Rev_Value = "";
			} else {
			}
		}
		log.debug("解析-k=" + getKey + " v=" + Rev_Value);
		return Rev_Value;
	}


	// 非空校验isNull
	public static boolean isNull(String value) {

		boolean reFlag = true;
		if (value == "" || value.length() <= 0) {
			reFlag = true;
		} else {
			reFlag = false;
		}
		log.debug(reFlag);
		return reFlag;
	}

	// 非空校验isNullMSG
	public static String isNullMSG(String key, String value) {

		String reResult = "";
		if (value == "" || value.length() <= 0) {
			reResult = key + "必填字段;";
		}
		return reResult;
	}

}
